<?php
namespace common\service;
use common\models\Balance;
use common\models\ExchangeLog;
use common\models\TradeExchange;
use common\models\Member;
/*
	兑换业务
*/

class ExchangeService
{

	/*
		兑换配置信息
		b_type
		member_id 会员id
	*/
	public static function conf($params)
	{
		$where = ['from_type' => $params['b_type']];
		$conf = TradeExchange::getAll($where);
		if(!$conf) return ['state' => false, 'msg' => '配置信息有误'];

		foreach($conf as &$val)
		{
			$bInfo = Balance::getBalance($params['member_id'], $val['to_type']);
			$val['balance'] = $bInfo['balance'];
			$val['type_name'] = $bInfo['type_name'];
			$val['price'] = $bInfo['price'];
		}
		$data = array();
		$data['conf'] = $conf;

		## 兑换账本的信息
		$bInfo = Balance::getBalance($params['member_id'], $params['b_type']);
		$data['balance'] = $bInfo;

		return ['state' => true , 'data'=>$data];
	}


	/*
		开始兑换
		* from_type 
		* to_type
		* money 
		* member_id
	*/
	public static function exchange($params, $member)
	{
		## 配置信息
		$conf = TradeExchange::getConf($params['from_type'], $params['to_type']);
		if(!$conf) return ['state' => false, 'msg' => '配置信息有误'];

		try{
			$transaction = \Yii::$app->db->beginTransaction();

			$res = self::condition($conf, $params);
			if(!$res['state']) throw new \Exception($res['msg']);

			## 创建日志
			if(!$logId = self::addLog($params, $conf)) throw new \Exception('日志生成失败');
			
			## 操作账本 减少
			$money1 = $conf['rate'] > 0 ? $params['money'] * ($conf['rate']+100)/100 : $params['money'];
			$money1 = round($money1, 2);
			$res = Balance::reduceBalance($params['member_id'], $conf['from_type'], $money1, 13, $logId, '兑换');
			if(!$res['state']) throw new \Exception($res['msg']);

			## 操作账本 增加
			$money2 = $params['money'] * $conf['price1'] / $conf['price2'];
			$money2 = $conf['multiple'] > 0 ? $money2 * $conf['multiple'] : $money2;
			$money2 = round($money2, 2);
			$res = Balance::addBalance($params['member_id'], $conf['to_type'], $money2, 13, $logId, '兑换');
			if(!$res['state']) throw new \Exception($res['msg']);
			
			if($conf['next_action']>0) echo '后续操作，暂省';

			$transaction->commit();
			return ['state' => true,'msg' => 'success'];
		}catch(\Exception $e)
		{
			$transaction->rollback();
			return ['state' => false,'msg' => $e->getMessage()]; 
		}		
	}

	//需要审核
    public static function exchange1($params, $member)
    {
        ## 配置信息
        $conf = TradeExchange::getConf($params['from_type'], $params['to_type']);
        if(!$conf) return ['state' => false, 'msg' => '配置信息有误'];

        try{
            $transaction = \Yii::$app->db->beginTransaction();

            $res = self::condition($conf, $params);
            if(!$res['state']) throw new \Exception($res['msg']);

            ## 创建日志
            if(!$logId = self::addLog($params, $conf, 1)) throw new \Exception('日志生成失败');

            ## 操作账本 减少
            $money1 = $conf['rate'] > 0 ? $params['money'] * ($conf['rate']+100)/100 : $params['money'];
            $money1 = round($money1, 2);
            $res = Balance::reduceBalance($params['member_id'], $conf['from_type'], $money1, 13, $logId, '兑换');
            if(!$res['state']) throw new \Exception($res['msg']);

            if($conf['next_action']>0) echo '后续操作，暂省';

            $transaction->commit();
            return ['state' => true,'msg' => 'success'];
        }catch(\Exception $e)
        {
            $transaction->rollback();
            return ['state' => false,'msg' => $e->getMessage()];
        }
    }

	## 条件
	private static function condition($conf, $params)
	{
		if(!$conf['state']) return ['state' => false , 'msg' => '暂不能此操作'];
		if($params['money'] <= 0) return ['state' => false,'msg' => '金额不能小于0'];
		if($conf['min_num'] > 0 && $conf['min_num'] > $params['money'] ) return ['state' => false, 'msg' => '金额不能小于'.$conf['min_num']];
		if($conf['max_num'] > 0 && $conf['max_num'] < $params['money'] ) return ['state' => false, 'msg' => '金额不能大于'.$conf['max_num']];
		if($conf['num_times'] > 0 && $params['money'] % $conf['num_times']) return ['state' => false, 'msg' => '金额要为'.$conf['num_times'].'的倍数'];

		$bInfo = Balance::getBalance($params['member_id'], $conf['from_type']);
		if($bInfo['balance'] < $params['money'] ) return ['state' => false , 'msg' => '余额不足'];

		return ['state' => true, 'msg' => 'success'];
	}	

	private static function addLog($params, $conf, $needCheck=0)
	{
		$data = array();
		$data['member_id'] = $params['member_id'];
		$data['from_money'] = $params['money'];
		$data['to_money'] = round($params['money'] * $conf['price1'] / $conf['price2'], 2);
		$data['from_type'] = $params['from_type'];
		$data['to_type'] = $params['to_type'];
		$data['price1'] = $conf['price1'];
		$data['price2'] = $conf['price2'];	
		$data['fee'] = round($params['money'] * $conf['rate']/100, 2);	
		$data['state'] = 1;
        if($needCheck!=0){
            $data['state'] = 2;
        }
		$data['create_time'] = time();

		$model = new ExchangeLog;
		if(!$model->load($data,'') || !$model->save()){
			return false;
			// var_dump($model->errors);
		}
		return \Yii::$app->db->getLastInsertId();
	}

}